package com.smartstate.EnvironmentMonitor.util;

import com.smartstate.EnvironmentMonitor.dto.common.TreeNode;
import com.smartstate.EnvironmentMonitor.entity.ObjMoudel;
import com.smartstate.EnvironmentMonitor.vo.EquipmentForTreeVO;
import org.springframework.beans.BeanUtils;
import org.springframework.util.CollectionUtils;

import java.util.*;
import java.util.stream.Collectors;

/**
 * <p>递归查楼宇</p>
 * <p>@Author 陈永杰</p>
 * <p>@Date: 2022/8/18</p>
 * <p>@Time: 11:36</p>
 * <p>@version 1.0 <p>
 */
public class ObjDemoUtils {
    public static List<TreeNode> getTreeNode(List<TreeNode> nodeList, List<EquipmentForTreeVO> equipmentList) {

        // 筛选根节点
        List<TreeNode> modelListObj = new ArrayList<>(nodeList.stream().filter(s ->  "0".equals(s.getParentId()))
                .collect(Collectors.toMap(TreeNode::getId, node -> node, (n1, n2) -> n1)).values());

        // 根据房屋Id分组
        Map<String, List<EquipmentForTreeVO>> equipmentMap = equipmentList.stream().collect(Collectors.groupingBy(EquipmentForTreeVO::getId));

        List<TreeNode> modelListTree = new ArrayList<>();

        Map<String,String> map = new HashMap<>();
        for (TreeNode treeNode : modelListObj) {
           TreeNode treeNodeObj = recursionFn(treeNode,nodeList,equipmentMap);
           modelListTree.add(treeNodeObj);
        }

        return modelListTree;
    }

    private static TreeNode recursionFn(TreeNode treeNode, List<TreeNode> modelList,
                                        Map<String, List<EquipmentForTreeVO>> equipmentMap) {
        List<TreeNode> treeNodeList = new ArrayList<>();
        modelList.forEach(e -> {
            if(treeNode.getId().equals(e.getParentId())){
                TreeNode treeNodeSon = new TreeNode();
                treeNode.setHasChild(true);
                BeanUtils.copyProperties(e, treeNodeSon);
                treeNodeSon.setParentId(treeNode.getId());
                treeNodeList.add(treeNodeSon);
                recursionFn(treeNodeSon, modelList,equipmentMap);
            }
        });
        treeNode.setEquipmentList(equipmentMap.get(treeNode.getId()));
        treeNode.setChildren(treeNodeList);
        if (CollectionUtils.isEmpty(treeNodeList)) {
            treeNode.setHasChild(false);
        }
        return treeNode;
    }



}